package com.project.core.aop;

import com.project.core.entity.Result;
import com.project.core.exception.ScoreException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author mengxj
 */
@Slf4j
@RestControllerAdvice
public class HandleException {

    @ExceptionHandler(ScoreException.class)
    public Result<String> handleServiceException(ScoreException e){
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return Result.fail(message);
    }

    @ExceptionHandler(BindException.class)
    public Result<String> bindException(BindException e){
        e.printStackTrace();
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return Result.fail(message);
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e){
        return this.handleCommon(e);
    }

    @ExceptionHandler(Throwable.class)
    public Result<String> handleThrowable(Throwable e){
        return this.handleCommon(e);
    }

    public Result<String> handleCommon(Throwable e){
        e.printStackTrace();
        return Result.fail(e.getMessage());
    }
}
